package socket2;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("客户端发起连接！");
            socket=new Socket("172.88.28.23",8088);
            System.out.println("客户端连接成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            Scanner scan=new Scanner(System.in);
            //获取输出流
            OutputStream os=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw=new BufferedWriter(osw);
            PrintWriter pw=new PrintWriter(bw,true);
            //
            //先输入昵称
            System.out.println("请输入昵称：");
            //判断昵称是否合法
            String nickName=scan.nextLine();
            while (nickName.trim().isEmpty()){
                System.out.println("昵称不能为空！请重新输入：");
                nickName=scan.nextLine();
            }

            //在此处阻塞等待输入昵称
            pw.println(nickName);
            System.out.println("欢迎你"+nickName+"，开始聊天吧！");
            //创建新的线程用于处理输入流，否则会阻塞
            Runnable clientHandler=new ClientHandler();
            Thread t=new Thread(clientHandler);
            t.setDaemon(true);//设置为守护线程
            t.start();


            while (true){
                String line=scan.nextLine();
                if (line.trim().isEmpty()){
                    System.out.println("输入不能为空！");
                    continue;
                }
                if ("exit".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line);
            }



        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client=new Client();
        client.start();
    }

    public class ClientHandler implements Runnable{
        public void run(){
            try {
                InputStream is= socket.getInputStream();
                InputStreamReader isr=new InputStreamReader(is,StandardCharsets.UTF_8);
                BufferedReader br=new BufferedReader(isr);
                //br.readLine();
                String message;

                while ((message=br.readLine())!=null) {
                    System.out.println(message);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }



}
